//
//  Pet_UserinfoViewController.swift
//  PetApp
//
//  Created by mac on 2023/9/21.
//  Copyright © 2023 Pet_. All rights reserved.
//

import UIKit

class Pet_UserinfoViewController: BasicViewController {

    let rightB = UIButton.initV(img: "icon_more(3)")
    var userID:String?{
        didSet{
            RT.getOtherUserInfoUrlInfoWith(userid: self.userID ?? "") { info in
                self.model = info
            }
            RT.careFriendState(idstring: userID ?? "") { s in
                self.followB.isSelected = s == "1"
                self.followB.setTitle(s == "1" ? "Unfollow" : "Follow", for: .normal)
                self.followB.backgroundColor = s == "1" ? UIColor.color(hexString: "#BBBBBB") : .black
                self.followB.setTitleColor(s == "1" ? UIColor.color(hexString: "#999999") : mainColor, for: .normal)
            }
            rightB.isHidden = userID == USEINFOMODEL.id
            
            RT.getRoomList { list in
                self.dataSource?.removeAll()
                for item in list.lists{
                    if item.info3 == "0" && item.createUserId == self.userID{
                        self.dataSource?.append(item)
                    }
                    
                    if item.info3 == "1" && item.createUserId == self.userID{
                        self.storydataSource?.append(item)
                    }

                }
                self.itemsTableView.reloadData()
                self.listView.reloadData()
            }

        }
    }
    var model: InfoUtil.initInfo?{
        didSet{
            if let url = URL(string: model?.headImage ?? "") {
                self.headimg.kf.setImage(with: url,placeholder: UIImage.init(named: "avarB"))
            }
            self.nameL.text = model?.name
        }
    }
    let headimg = UIImageView.initImgView(img: "avarB")
    let nameL = UILabel.initV(UIFont.setTypeFace(18,type: .bold), text: "", textColor: titleColor)
    let messageB = UIButton.initV(img: "iconasd")
    let callB = UIButton.initV(img: "callinfo")
    private lazy var followB: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = .setTypeFace(14.Fit,type: .medium)
        button.setTitleColor(.white, for: .normal)
        button.setTitle("Follow", for: .normal)
        button.backgroundColor = mainColor
        button.tag = 100
        return button
    }()
    let botomV = UIView.init(frame: .zero)
    let itemV1 = UIView.init(frame: .zero)
    let itemV2 = UIView.init(frame: .zero)
    let itemV3 = UIView.init(frame: .zero)

    let titL1 = UILabel.initV(UIFont.setTypeFace(12,type: .medium), text: "Followers", textColor: .color(hexString: "#999999"))
    let numL1 = UILabel.initV(UIFont.setTypeFace(18,type: .medium), text: "", textColor: titleColor)

    let titL2 = UILabel.initV(UIFont.setTypeFace(12,type: .medium), text: "Following", textColor: .color(hexString: "#999999"))
    let numL2 = UILabel.initV(UIFont.setTypeFace(18,type: .medium), text: "", textColor: titleColor)

    let titL3 = UILabel.initV(UIFont.setTypeFace(12,type: .medium), text: "Post", textColor: .color(hexString: "#999999"))
    let numL3 = UILabel.initV(UIFont.setTypeFace(18,type: .medium), text: "", textColor: titleColor)

    private lazy var listView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 5.Fit
        layout.minimumInteritemSpacing = 5.Fit
        layout.itemSize = .init(width: screenWidth/2 - 30/2, height: 200.Fit)
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.register(MomentList_Item.self, forCellWithReuseIdentifier: MomentList_Item.description())
        view.backgroundColor = .clear
        view.contentInset = .init(top: 0, left: 5.Fit, bottom: 0, right: 5.Fit)
        view.delegate = self
        view.dataSource = self
        view.bounces = false
        return view
    }()
    
    private lazy var itemsTableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .clear
        view.register(StoryCell.self, forCellReuseIdentifier: StoryCell.description())
        view.rowHeight = UITableView.automaticDimension
        return view
    }()

    var dataSource:[InfoUtil.room]? = []
    
    var storydataSource:[InfoUtil.room]? = []

    let btn1 = UIButton.initV(font: UIFont.setTypeFace(18,type: .medium), text: "Moment", img: "")
    let btn2 = UIButton.initV(font: UIFont.setTypeFace(18,type: .medium), text: "Story", img: "")
    let lineL = UILabel.init(frame: .zero)
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        RT.fansNumAction(idstring: self.userID ?? "") { info in
            self.numL1.text = info.num
        }

        RT.careNumAct(idstring: self.userID ?? "") { info in
            self.numL2.text = info.num
        }
        RT.getRoomList { list in
            var num = 0
            for item in list.lists{
                if item.createUserId == self.userID {
                    num += 1
                }
            }
            self.numL3.text = "\(num)"
        }


    }
    let imgB = UIImageView.initImgView(img: "cardtop")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.setRightItem(rightB)
        rightB.addAct {
            let page = Edit_Choose_Photo_Interface(type: .reportAndBlock(userId: self.model?.id?.intValue ?? 0,personal: true))
            self.present(page, animated: true)
        }
        view.subviews {
            imgB
            headimg
            nameL
            itemV1.subviews {
                titL1
                numL1
            }
            itemV2.subviews {
                titL2
                numL2
            }
            itemV3.subviews {
                titL3
                numL3
            }
            btn1
            btn2
            lineL
            listView
            itemsTableView
            botomV.subviews {
                messageB
                callB
                followB
            }
            
        }
        
        
        imgB.left(0).right(0).top(0).height(150.Fit)
        headimg.size(110.Fit).top(NavHeight + 20.Fit)
        headimg.centerHorizontally()
        headimg.setAllCorners(corner: 55.Fit)
        
        nameL.left(20).right(20).height(25.Fit)
        nameL.Top == headimg.Bottom + 10.Fit
        nameL.textAlignment = .center
        
        botomV.left(0).right(0).bottom(0).height(TabbarHeight)
        botomV.isUserInteractionEnabled = true
        botomV.backgroundColor = .white
        
        itemV2.backgroundColor = .white
        itemV2.width(100.Fit).height(120.Fit)
        itemV2.Top == nameL.Bottom + 15.Fit
        itemV2.centerHorizontally()
        itemV2.setAllCorners(corner: 20.Fit)
        titL2.textAlignment = .center
        titL2.left(0).right(0).bottom(30.Fit).height(20.Fit)
        numL2.textAlignment = .center
        numL2.left(0).right(0).top(30.Fit).height(20.Fit)
        
        itemV1.backgroundColor = .white
        itemV1.width(100.Fit).height(120.Fit)
        itemV1.Top == nameL.Bottom + 20.Fit
        itemV1.Trailing == itemV2.Leading - 15.Fit
        itemV1.setAllCorners(corner: 20.Fit)
        titL1.textAlignment = .center
        titL1.left(0).right(0).bottom(30.Fit).height(20.Fit)
        numL1.textAlignment = .center
        numL1.left(0).right(0).top(30.Fit).height(20.Fit)

        itemV3.backgroundColor = .white
        itemV3.width(100.Fit).height(120.Fit)
        itemV3.Top == nameL.Bottom + 15.Fit
        itemV3.Leading == itemV2.Trailing + 20.Fit
        itemV3.setAllCorners(corner: 20.Fit)
        titL3.textAlignment = .center
        titL3.left(0).right(0).bottom(30.Fit).height(20.Fit)
        numL3.textAlignment = .center
        numL3.left(0).right(0).top(30.Fit).height(20.Fit)
        
        btn1.width(85.Fit).height(30.Fit).left(15.Fit)
        btn1.Top == itemV3.Bottom + 30.Fit
        btn1.addAct {
            var rect = self.lineL.frame
            rect.origin.x = self.btn1.center.x - 20.Fit
            self.lineL.frame = rect
            self.listView.isHidden = false
            self.itemsTableView.isHidden = true
        }
        
        btn2.width(85.Fit).height(30.Fit)
        btn2.Top == itemV3.Bottom + 30.Fit
        btn2.Leading == btn1.Trailing + 40.Fit
        btn2.addAct {
            var rect = self.lineL.frame
            rect.origin.x = self.btn2.center.x - 20.Fit
            self.lineL.frame = rect
            self.listView.isHidden = true
            self.itemsTableView.isHidden = false
        }
        
        lineL.width(50.Fit).height(2.Fit)
        lineL.backgroundColor = .black
        lineL.Top == btn1.Bottom
        lineL.CenterX == btn1.CenterX
        
        
        callB.left(15.Fit).top(15.Fit).height(40.Fit).width(60.Fit)
        callB.addAct {
            guard self.model?.id != USEINFOMODEL.id else {
                return
            }
            UIImageView.downloadWith(urlStr: self.model?.headImage ?? "") { img in
                let vc = TEA_VideoViewController()
                vc.peerStr = self.model?.id
                vc.isRecept = false
                vc.headImage = img
                vc.nameStr = self.model?.name
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
        messageB.top(15.Fit).height(40.Fit).width(60.Fit)
        messageB.Leading == callB.Trailing + 10.Fit
        messageB.addAct {
            guard self.model?.id != USEINFOMODEL.id else {
                return
            }
            let vc = TEA_ChatViewController()
            vc.targetId = self.model?.id
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        followB.right(15.Fit).top(15.Fit).height(40.Fit)
        followB.Leading == messageB.Trailing + 10.Fit
        followB.setAllCorners(corner: 20.Fit)
        followB.addAct {
            guard self.model?.id != USEINFOMODEL.id else {
                Toast_View_Tool.show(type: .error,text: "You can't follow yourself")
                return
            }
            Toast_View_Tool.show()
            let type = self.followB.isSelected == true ? "0" : "1"
            RT.AddDeleteFriend(idstring: self.model?.id ?? "", type: type) { s in
                Toast_View_Tool.dismiss()
                self.followB.isSelected = !self.followB.isSelected
                self.followB.setTitle(s == "1" ? "Unfollow" : "Follow", for: .normal)
                self.followB.backgroundColor = s == "1" ? UIColor.color(hexString: "#BBBBBB") : .black
                self.followB.setTitleColor(s == "1" ? UIColor.color(hexString: "#999999") : mainColor, for: .normal)
            }
        }
        
        listView.left(0).right(0)
        listView.Top == lineL.Bottom + 10.Fit
        listView.Bottom == botomV.Top - 10.Fit
        
        
        itemsTableView.left(0).right(0)
        itemsTableView.Top == lineL.Bottom + 10.Fit
        itemsTableView.Bottom == botomV.Top - 10.Fit
        itemsTableView.isHidden = true
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name("BlockRefreshNotice"), object: nil, queue: nil) {[weak self] noti in
            self?.navigationController?.popViewController(animated: true)
        }

    }

}


extension Pet_UserinfoViewController:UICollectionViewDelegate,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let item = collectionView.dequeueReusableCell(withReuseIdentifier: MomentList_Item.description(), for: indexPath) as! MomentList_Item
        item.model = dataSource?[indexPath.item]
        return item
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = Pet_CardDetailViewController()
        vc.model = dataSource?[indexPath.item]
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension Pet_UserinfoViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return storydataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: StoryCell.description(), for: indexPath) as! StoryCell
        cell.model = storydataSource?[indexPath.row]
        return cell
    }
        
}




class MomentList_Item: UICollectionViewCell {
    
    let coverI = UIImageView.initImgView(img: "")
    let nameL = UILabel.initV(UIFont.setTypeFace(16,type: .medium), text: "", textColor: .white)
    let avarB = UIButton.initV(img: "")
    var model:InfoUtil.room?{
        didSet{
            let arr = self.model?.info2?.components(separatedBy: "@@")
            if let url = URL(string:arr?.first ?? "") {
                self.coverI.kf.setImage(with: url)
            }
            self.nameL.text = model?.info
            if let url = URL(string: self.model?.icon ?? "") {
                self.avarB.kf.setImage(with: url, for: .normal)
            }
            self.collectb.isSelected = Pet_CollectManager.shared.CollectList().contains(where: {$0.id == self.model?.id})
        }
    }
    let collectb = UIButton.initV(img: "icon_favorite_on1")
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.subviews {
            coverI.subviews {
                avarB
                nameL
                collectb
            }
        }
        coverI.fillContainer()
        coverI.setAllCorners(corner: 20.Fit)
        
        avarB.bottom(15.Fit).left(15.Fit).size(50.Fit)
        avarB.setAllCorners(corner: 25.Fit)
        
        nameL.height(25.Fit).right(15.Fit)
        nameL.Leading == avarB.Trailing + 15.Fit
        nameL.CenterY == avarB.CenterY
        
        collectb.right(10.Fit).top(10.Fit).size(40.Fit)
        collectb.setImage(.init(named: "icon_favorite_on1 1"), for: .selected)
        collectb.addAct {
            self.collectb.isSelected = !self.collectb.isSelected
            if self.collectb.isSelected == true{
                Pet_CollectManager.shared.saveRecord(.init(id: self.model?.id ?? ""))
            }else
            {
                Pet_CollectManager.shared.deleteRecord(.init(id: self.model?.id ?? ""))
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

